package com.apexedu.biz.service.impl;

import java.security.Principal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.apexedu.biz.entity.TAccessAppReg;
import com.apexedu.biz.entity.client.CommandResult;
import com.apexedu.biz.entity.client.ResourceEntity;
import com.apexedu.biz.entity.client.ResourceForshdEntity;
import com.apexedu.biz.entity.client.RoleEntity;
import com.apexedu.framework.dao.BaseDao;
import com.apexedu.framework.util.ConfigUtil;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.identity.entity.TSysMenu;
import com.apexedu.identity.entity.TSysRole;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.support.cache.CacheUtils;
import com.apexedu.sys.SysConstant;
import com.apexedu.sys.util.BusinessLogUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.crypto.CipherUtil;

/**
 * 对资源的操作，都单独提取到这个类了。
 * User: 杨建亮
 * Date: 13-12-13 下午4:29
 */
public abstract class ResourceServiceImpl {

	@SuppressWarnings("unused")
	private static final Log LOG = LogFactory.getLog(ResourceServiceImpl.class);

	public static final String SecKey = CipherUtil.getAESKeyAsString("ApexAuCAuthKey"); // 和AuthClient客户端约定好的对称加密密钥
	private static final String portalKey = ConfigUtil.getString("portalCode");//门户接入号
	@Autowired
	protected BaseDao baseDao;

	/**
	 * 查询当前用户权限下的所有资源
	 *
	 * @param request 登录用户
	 * @return List<ResourceEntity>
	 */
	@Deprecated
	public CommandResult getMyResources(HttpServletRequest request) {
		//        String userLoginId = (String)request.getAttribute("userLoginId");
		Principal principal = request.getUserPrincipal();
		String userLoginId = principal.getName();
		String clientAppId = request.getHeader("AuC");
		return getResourcesByAssignUser(clientAppId, userLoginId);
	}

	/**
	 * 查询指定用户权限下的所有资源
	 *
	 * @param userLoginId 用户登录账户
	 * @return List<ResourceEntity>
	 */
	@Transactional(readOnly = true)
	public CommandResult getResourcesByAssignUser(String clientAppId, String userLoginId) {

		clientAppId = checkClientAppId(clientAppId); // 断言接入号正确

		CommandResult result = new CommandResult();
		if (StringUtils.isBlank(userLoginId)) {
			result.setHasError(true);
			result.setError("无效的用户标识");
		} else {
			String cacheKey = "GetRes" + userLoginId + clientAppId;

			List<ResourceEntity> authEntities = (List<ResourceEntity>) CacheUtils.get(cacheKey); // 缓存
			if (authEntities == null || authEntities.size() == 0) {
				authEntities = new ArrayList<ResourceEntity>();
				StringBuilder hql = new StringBuilder("select e from TSysUser a, TSysUserRole b, TSysRole c, TSysRoleMenu d, TSysMenu e " + "where a.userid=b.userid and b.roleid=c.roleid and c.roleid=d.roleid and d.menuid=e.menuid "
						+ "and a.userloginid=? and c.state=1 and e.state=1 ");
				List<Object> params = new LinkedList<Object>();
				params.add(userLoginId);
				if (portalKey.equals(clientAppId)) {//如果为门户信息
					hql.append(" and e.sftjdmh = '1' ");
				} else {
					hql.append(" and e.belongtoapp= ? ");
					params.add(clientAppId);
				}
				List<TSysMenu> menus = baseDao.findByHql(hql.toString(), params.toArray());
				for (TSysMenu menu : menus) {
					ResourceEntity resourceEntity = new ResourceEntity();
					resourceEntity.setHasRights(true);
					resourceEntity.setUserLoginId(userLoginId);
					resourceEntity.setAppId(clientAppId);
					resourceEntity.setSrcId(menu.getBizcode());
					resourceEntity.setSrcRealUrl(menu.getMenupath());
					resourceEntity.setSrcTitle(menu.getMenuname());
					resourceEntity.setSrcType(menu.getSrctype());
					authEntities.add(resourceEntity);
				}
				CacheUtils.put(cacheKey, authEntities); // 缓存
			}
			result.setResourceEntities(authEntities);
		}
		return result;
	}

	/**
	 * 查询门户下面的所有资源
	 *
	 * @param clientAppId
	 * @return
	 */
	public CommandResult getPortalResources(String clientAppId) {
		clientAppId = checkClientAppId(clientAppId);
		CommandResult result = new CommandResult();
		if (portalKey.equals(clientAppId)) {
			String cacheKey = "GetRes" + clientAppId;
			List<ResourceEntity> authEntities = (List<ResourceEntity>) CacheUtils.get(cacheKey); // 缓存
			if (null == authEntities || authEntities.size() == 0) {
				authEntities = new ArrayList<ResourceEntity>();
				String hql = " from TSysMenu t where t.sftjdmh='1'";
				List<TSysMenu> menus = baseDao.findByHql(hql.toString());
				for (TSysMenu menu : menus) {
					ResourceEntity resourceEntity = new ResourceEntity();
					resourceEntity.setHasRights(true);
					resourceEntity.setAppId(menu.getMenuid());
					resourceEntity.setSrcId(menu.getBizcode());
					resourceEntity.setSrcRealUrl(menu.getMenupath());
					resourceEntity.setSrcTitle(menu.getMenuname());
					resourceEntity.setSrcType(menu.getSrctype());
					authEntities.add(resourceEntity);
				}
				CacheUtils.put(cacheKey, authEntities); // 缓存
			}
			result.setResourceEntities(authEntities);
		}
		return result;
	}

	/**
	 * 保存客户端提交的资源数据。此方法为增量同步，如果已存在的，就执行更新操作。
	 *
	 * @param dataList 资源集合
	 * @param clientAppId 接入号
	 * @return
	 */
	public CommandResult uploadResourcesBySTA(List<ResourceEntity> dataList, String clientAppId) {
		CommandResult result = new CommandResult();
		clientAppId = checkClientAppId(clientAppId); // 断言接入号正确
		if (dataList != null && dataList.size() > 0) {
			List<TSysMenu> existMenus = findExistResources(dataList, clientAppId); // 里面判断了资源编号必须要存在和已经存在的资源
			List<ResourceEntity> newResourcesList = findNewResourcesAndUpdateExist(dataList, existMenus); // 已存在的资源被过滤掉了，值放在了existResources中。
			/******************************** 判断，如果资源是由门户同步过来的，则再进行一次资源过滤 **********************************/
			if (portalKey.equals(clientAppId)) {
				System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!进入门户筛选方法");
				existMenus = findExistResourceByPortal(dataList);//判断权限中心已经存在的资源。
				newResourcesList = finNewResourcesByPortal(newResourcesList, existMenus);
			}
			List<TSysMenu> newMenus = new ArrayList<TSysMenu>(dataList.size());
			for (int i = 0; i < newResourcesList.size(); i++) {
				ResourceEntity resourceEntity = newResourcesList.get(i);
				if (StringUtils.isBlank(resourceEntity.getAppId())) {
					resourceEntity.setAppId(clientAppId);
				} else {
					// 如果有资源所属人（系统），则可以判断和提交人是否同一人
				}
				TSysMenu sysMenu = new TSysMenu(); //资源ID 这个ID由我们权限中心自动生成
				// 1.获取上级编号
				String parentMenuId;
				if (StringUtils.isBlank(resourceEntity.getSrcUpId())) {
					parentMenuId = "000"; // 默认放业务系统的根节点下。
				} else {
					// 如果有值，就查询此父节点的对应的编号（我们自己的内部编号）。
					parentMenuId = getParentMenuId(newMenus, resourceEntity.getSrcUpId()); // 因为是批量保存。上一个（父）节点还没有保存到数据库，所以要在集合中先查找。
					if (StringUtils.isBlank(parentMenuId)) {
						String sql = "select menuid from t_sys_menu where belongtoapp=? and bizcode=?";
						parentMenuId = (String) DBUtil.queryFieldValue(sql, clientAppId, resourceEntity.getSrcUpId());
					}
				}
				if (StringUtil.isEmpty(parentMenuId)) { //避免发生空指针 TODO:这地方还需要优化，因为在备份的过程中发现有的系统同意过来找不到父节点
					parentMenuId = "000"; //放在业务系统的根节点
				}
				sysMenu.setUpmenuid(parentMenuId); //上级资源
				// 2.根据上级编号生成此节点编号
				String parentID;
				try {
					parentID = getNewMenuIdByParentMenuId(newMenus, parentMenuId);
					//验证parentID是否已经存在，如果存在则自动增加一位。返回新parentID

					sysMenu.setMenuid(parentID);
				} catch (Exception e) {
					LOG.error(e);
					result.setHasError(true);
					result.setError("操作失败：生成资源索引失败！请通知管理员。srcid:" + resourceEntity.getSrcId());
					throw new RuntimeException("操作失败：生成资源索引失败！请通知管理员。");
				}
				sysMenu.setMenuname(resourceEntity.getSrcTitle()); //标题
				sysMenu.setMenupath(resourceEntity.getSrcRealUrl()); //资源URL
				sysMenu.setBelongtoapp(clientAppId); //业务系统编号
				sysMenu.setSrctype(resourceEntity.getSrcType()); //资源类型
				sysMenu.setBizcode(resourceEntity.getSrcId()); //原业务系统中的资源ID
				sysMenu.setUpbizcode(resourceEntity.getSrcUpId());
				sysMenu.setOrdernum(100);
				sysMenu.setState("1");
				sysMenu.setIsshare("0");
				sysMenu.setDepth(Short.decode(String.valueOf(parentID.length() / 3)));
				newMenus.add(sysMenu);
			}
			baseDao.saveAll(newMenus); // 保存新增加的资源
			BusinessLogUtil.log(clientAppId, SysConstant.CZDX_T_SYS_MENU, SysConstant.LOG_ACTION_SAVE, clientAppId);
			for (int j = 0; j < existMenus.size(); j++) {
				baseDao.update(existMenus.get(j));
			}
			BusinessLogUtil.log(clientAppId, SysConstant.CZDX_T_SYS_MENU, SysConstant.LOG_ACTION_UPDATE, clientAppId);
		}
		return result;
	}

	/**
	 * 删除资源。同时删除对应的关系（角色-资源）
	 *
	 * @param dataList 资源集合
	 * @param clientAppId 接入号
	 * @return
	 */
	public CommandResult deleteResourcesBySTA(List<ResourceEntity> dataList, String clientAppId) {

		clientAppId = checkClientAppId(clientAppId); // 断言接入号正确

		ArrayList<String> params = new ArrayList<String>(dataList.size());
		// 1.删除资源、角色关系
		StringBuilder sql = new StringBuilder("delete from t_sys_role_menu a where exists (select 1 from t_sys_menu b where a.menuid=b.menuid and b.belongtoapp=? and ");
		params.add(clientAppId);
		sql.append(getSqlWhereAndSetParams(dataList, params));
		sql.append(")");
		DBUtil.executeSQL(sql.toString(), params.toArray());
		BusinessLogUtil.log(clientAppId, SysConstant.CZDX_T_SYS_ROLE_MENU, SysConstant.LOG_ACTION_DEL, clientAppId);
		// 2.删除资源

		getUpMenuIdBySTA(dataList, clientAppId);

		CommandResult result = new CommandResult();
		return result;
	}

	/**
	 * 从数据库查询出已存在的资源对象集合
	 *
	 * @param dataList
	 * @param clientAppId
	 * @return
	 */
	private List<TSysMenu> findExistResources(List<ResourceEntity> dataList, String clientAppId) {

		// 查询此资源是否已经存在数据库里
		StringBuilder hql = new StringBuilder("from TSysMenu b where b.belongtoapp=? and ");
		ArrayList<String> params = new ArrayList<String>(dataList.size());
		params.add(clientAppId);
		hql.append(getSqlWhereAndSetParams(dataList, params));
		List<TSysMenu> sysMenus = baseDao.findByHql(hql.toString(), params.toArray());
		return sysMenus;
	}

	private StringBuilder getSqlWhereAndSetParams(List<ResourceEntity> dataList, ArrayList<String> params) {
		StringBuilder hql = new StringBuilder("(");
		for (int i = 0; i < dataList.size(); i++) {
			ResourceEntity resourceEntity = dataList.get(i);
			Assert.hasText(resourceEntity.getSrcId(), resourceEntity.getSrcTitle() + "的资源编号不能为空");
			hql.append(" b.bizcode=? or");
			params.add(resourceEntity.getSrcId());
		}
		hql.delete(hql.length() - 2, hql.length());
		hql.append(")");
		return hql;
	}

	/**
	 * 从用户提交的资源集合里，找出新提交的资源。用existMenus来判断。
	 * 同时更新existMenus里已存在资源的值，便于后续hibernate更新。
	 *
	 * @param dataList 客户端提供的完整资源集合
	 * @param existMenus 客户端提交的资源中，在服务器已经存在的资源集合
	 * @return 新增加的资源的集合
	 */
	private List<ResourceEntity> findNewResourcesAndUpdateExist(List<ResourceEntity> dataList, List<TSysMenu> existMenus) {

		List<ResourceEntity> newResources = new ArrayList<ResourceEntity>(dataList.size() - existMenus.size());
		for (int i = 0; i < dataList.size(); i++) {
			ResourceEntity resourceEntity = dataList.get(i);
			boolean isNewResource = true; // 假设这个资源是新的资源，数据库中不存在
			for (int j = 0; j < existMenus.size(); j++) {
				TSysMenu sysMenu = existMenus.get(j);
				if (resourceEntity.getSrcId().equals(sysMenu.getBizcode())) {
					isNewResource = false;
					// 更新数据库里的资源对象
					if (StringUtils.isNotBlank(resourceEntity.getSrcTitle())) {
						sysMenu.setMenuname(resourceEntity.getSrcTitle()); //标题
					}
					if (StringUtils.isNotBlank(resourceEntity.getSrcRealUrl())) {
						sysMenu.setMenupath(resourceEntity.getSrcRealUrl()); //资源URL
					}
					if (StringUtils.isNotBlank(resourceEntity.getSrcType())) {
						sysMenu.setSrctype(resourceEntity.getSrcType()); //资源类型
					}
					baseDao.update(sysMenu);//更新数据库
					break;
				}
			}
			if (isNewResource) {
				newResources.add(resourceEntity);
			} else {
				dataList.remove(i);
				i--;
			}
		}
		return newResources;
	}

	private String getParentMenuId(List<TSysMenu> sysMenus, String menuId) {
		for (TSysMenu menu : sysMenus) {
			if (menuId.equalsIgnoreCase(menu.getBizcode())) {
				return menu.getMenuid();
			}
		}
		return null;
	}

	/**
	 * 断言接入号合法性；断言接入站点就是登记注册时填写的网址
	 *
	 * @param clientAppId 加密的接入号
	 * @return 解密后的接入号
	 */
	public String checkClientAppId(String clientAppId) {
		if (StringUtils.isBlank(clientAppId)) {
			LOG.error("接收到一次非法的请求 [ miss ClientAppId ] ");
			throw new RuntimeException("非法请求！");
		} else {
			clientAppId = CipherUtil.decryptByAES(clientAppId, SecKey); // 解密
			String cacheKey = "AuthApp" + clientAppId;
			TAccessAppReg appReg = (TAccessAppReg) CacheUtils.get(cacheKey); // 缓存
			if (appReg == null) {
				List<TAccessAppReg> appRegs = baseDao.findByHqlWithSecondCache(true, "from TAccessAppReg where appid=?", clientAppId);
				if (appRegs == null || appRegs.isEmpty()) {
					LOG.error("接收到一次无效的请求 [ not exist ClientAppId : " + clientAppId + " ] ");
					throw new RuntimeException("无效请求！");
				} else { // 缓存起来
					CacheUtils.put(cacheKey, appRegs.get(0));
				}
			}
		}
		return clientAppId;
	}

	/**
	 * 生成新的ID号 规则：根据父ID查询其下一级最大的ID号，然后增加一。
	 *
	 * @param parentid
	 * @return 新的ID号
	 * @throws Exception
	 */
	public static String getNewMenuIdByParentMenuId(List<TSysMenu> menuList, String parentid) throws Exception {
		parentid = SeqFactory.getNewTreeIdByParentId("T_Sys_Menu", "menuid", "upMenuId", parentid);
		//判断menuid是否存在
		if (null != menuList && menuList.size() > 0) {
			for (TSysMenu tSysMenu : menuList) {
				if (tSysMenu.getMenuid().equals(parentid)) { //如果存在
					//判断paraent长度是否超过15如果超过则将其分为两端（主要防止后米娜转为long类型是超过long最高长度）
					if (parentid.length() > 15) {
						String parentA = parentid.substring(0, 15);
						String parentB = parentid.substring(15, parentid.length());
						String parentC = String.valueOf(Long.parseLong(parentB) + 1);//自加一
						//执行补零
						for (int i = 0; i < (parentB.length() - parentC.length()); i++) {
							parentC = "0" + parentC;
						}
						parentid = parentA + "0" + parentC;//还原parentid值
					} else {
						String parentidA = String.valueOf(Long.parseLong(parentid) + 1);
						for (int i = 0; i < (parentid.length() - parentidA.length()); i++) {
							parentidA = "0" + parentidA;
						}
						parentid = "0" + parentidA;
					}
				}
			}
		}
		return parentid;
	}

	private void getUpMenuIdBySTA(List<ResourceEntity> dataList, String clientAppId) {
		if (null != dataList) {
			//第一步，查询需要删除的节点对象
			StringBuilder sqllist = new StringBuilder(" select * from T_SYS_MENU t where 1 = 1 and t.belongtoapp = ? and ");
			StringBuilder hql = new StringBuilder();
			List<Object> params = new LinkedList<Object>();
			params.add(clientAppId);
			for (int i = 0; i < dataList.size(); i++) {
				ResourceEntity resourceEntity = dataList.get(i);
				if (StringUtils.isNotBlank(resourceEntity.getSrcId())) {
					if (i < dataList.size() - 1) {
						hql.append(" t.bizcode = ? or ");
						params.add(resourceEntity.getSrcId());
					} else {
						hql.append(" t.bizcode= ? ");
						params.add(resourceEntity.getSrcId());
					}
				}
			}
			sqllist.append(hql);
			List<TSysMenu> sysMenuList = DBUtil.queryAllBeanList(sqllist.toString(), TSysMenu.class, params.toArray());
			//第二步，先删除dataList中需要删除的对象，因为下面需要清空params中的内容
			StringBuilder sql = new StringBuilder("delete from  T_SYS_MENU t  where 1 = 1 and t.belongtoapp = ? and ");
			sql.append(hql);
			DBUtil.executeSQL(sql.toString(), params.toArray());
			BusinessLogUtil.log(clientAppId, SysConstant.CZDX_T_SYS_MENU, SysConstant.LOG_ACTION_DEL, clientAppId);
			//第三步，查询父节点为以上节点的所有节点
			if (null != sysMenuList && sysMenuList.size() > 0) {
				params.clear();//每次循环前清空params里面的值
				params.add(clientAppId);
				StringBuilder hql_MenuId = new StringBuilder();
				for (int i = 0; i < sysMenuList.size(); i++) {
					TSysMenu tSysMenu = sysMenuList.get(i);
					if (StringUtils.isNotBlank(tSysMenu.getMenuid())) {
						if (i < sysMenuList.size() - 1) {
							hql_MenuId.append(" t.upmenuid like'" + tSysMenu.getMenuid() + "%' or ");
						} else {
							hql_MenuId.append(" t.upmenuid like'" + tSysMenu.getMenuid() + "%'");
						}
					}
				}
				StringBuilder delete_List = new StringBuilder(" delete from  T_SYS_MENU t  where 1 = 1 and t.belongtoapp = ? and ");
				delete_List.append(hql_MenuId);
				DBUtil.executeSQL(delete_List.toString(), params.toArray());
				BusinessLogUtil.log(clientAppId, SysConstant.CZDX_T_SYS_MENU, SysConstant.LOG_ACTION_DEL, clientAppId);
			}
		}
	}

	/**
	 * 查询指定资源下的所有角色
	 *
	 * @param resourceid 资源ID
	 * @return List<ResourceEntity>
	 */
	@Transactional(readOnly = true)
	public CommandResult getRoleByResource(String clientAppId, String resourceid) {

		clientAppId = checkClientAppId(clientAppId); // 断言接入号正确

		CommandResult result = new CommandResult();
		if (StringUtils.isBlank(resourceid)) {
			result.setHasError(true);
			result.setError("无效的资源ID");
		} else {
			String cacheKey = "GetRoleByResource" + resourceid + clientAppId;

			List<RoleEntity> authEntities = (List<RoleEntity>) CacheUtils.get(cacheKey); // 缓存
			if (authEntities == null) {
				authEntities = new ArrayList<RoleEntity>();
				/*
				 * String hql = "select e from TSysUser a, TSysUserRole b, TSysRole c, TSysRoleMenu d, TSysMenu e " +
				 * "where a.userid=b.userid and b.roleid=c.roleid and c.roleid=d.roleid and d.menuid=e.menuid " +
				 * "and a.userloginid=? and e.belongtoapp=? and c.state=1 and e.state=1";
				 */

				String hql = "select b from TSysRoleMenu a,TSysRole b,TSysMenu c where a.roleid =b.roleid and a.menuid=c.menuid and  a.menuid=? and c.belongtoapp=? and c.state=1";
				List<TSysRole> sysRoles = baseDao.findByHql(hql, resourceid, clientAppId);

				for (TSysRole role : sysRoles) {
					RoleEntity roleEntity = new RoleEntity();
					roleEntity.setRoleId(role.getRoleid());
					roleEntity.setRoleName(role.getRolename());
					roleEntity.setMemo(role.getMemo());
					roleEntity.setRoleState(role.getState());

					authEntities.add(roleEntity);
				}
				CacheUtils.put(cacheKey, authEntities); // 缓存
			}
			result.setRoleEntities(authEntities);
		}
		return result;
	}

	/**
	 * 查询出，门户中已经存在的资源
	 *
	 * @param dataList
	 * @return
	 */
	public List<TSysMenu> findExistResourceByPortal(List<ResourceEntity> dataList) {
		List<Object> params = new LinkedList<Object>();
		int i = 0;//标记第一个符合条件的资源
		System.out.println("++++++++++++开始循环+++++++++++++");
		StringBuilder hql = new StringBuilder("");
		for (ResourceEntity resourceEntity : dataList) {

			if (StringUtil.isNotBlank(resourceEntity.getAppId())) {//如果资源wid不为空
				if (0 == i) {//如果为第一个
					hql.append(" select * from t_sys_menu t where 1 = 1  and t.menuid = ? ");
					params.add(resourceEntity.getAppId());
					System.out.println("**************************AppId:" + resourceEntity.getAppId());
				} else {
					hql.append(" or t.menuid = ? ");
					params.add(resourceEntity.getAppId());
					System.out.println("**************************AppId:" + resourceEntity.getAppId());
				}
				i++;
			}
		}
		System.out.println("SQL:" + hql.toString());
		/******************** 如果存在符合条件的资源 **********************/
		if (0 != i && null != params) {
			List<TSysMenu> list = DBUtil.queryAllBeanList(hql.toString(), TSysMenu.class, params.toArray());
			return list;
		}
		return null;
	}

	/**
	 * 将门户上传过来的资源进行第二次过滤，这次过滤主要根据 menuid来过滤。
	 *
	 * @param entityList
	 * @param list
	 * @return
	 */
	public List<ResourceEntity> finNewResourcesByPortal(List<ResourceEntity> entityList, List<TSysMenu> list) {
		if (null != list && list.size() > 0) {
			if (null != entityList && entityList.size() > 0) {
				List<ResourceEntity> resourceEntityList = new LinkedList<ResourceEntity>();
				for (ResourceEntity resourceEntity : entityList) {
					boolean msg = true;//默认不存在
					if (StringUtil.isNotBlank(resourceEntity.getAppId())) {
						for (TSysMenu tSysMenu : list) {
							if (resourceEntity.getAppId().equals(tSysMenu.getMenuid())) {
								msg = false;
								break;
							} else {
								msg = true;
							}
						}
					}
					if (msg) {
						resourceEntityList.add(resourceEntity);
					}
				}
				return resourceEntityList;
			}
		}
		return entityList;
	}

	/**
	 * 查询学生/教工基本信息
	 *
	 * @param userLoginId 用户登录账户
	 * @return List<ResourceEntity>
	 */
	@Transactional(readOnly = true)
	public ResourceForshdEntity getResourcesByShdUser(String clientAppId, String userLoginId) {

		clientAppId = checkClientAppIdShd(clientAppId); // 断言接入号正确
		ResourceForshdEntity entity = new ResourceForshdEntity();
		CommandResult result = new CommandResult();
		if (StringUtils.isBlank(userLoginId)) {
			result.setHasError(true);
			result.setError("无效的用户标识");
		} else {
			String cacheKey = "GetRes" + userLoginId + clientAppId;
			List<ResourceForshdEntity> authEntities = (List<ResourceForshdEntity>) CacheUtils.get(cacheKey); // 缓存
			if (authEntities == null || authEntities.size() == 0) {
				authEntities = new ArrayList<ResourceForshdEntity>();
				String user_hql = "select * from TSysUser where userloginid=?";
				TSysUser tsysuser = baseDao.findBean(user_hql, userLoginId);
				if ("2".equals(tsysuser.getUsertype())) {
					user_hql = "  select userloginid as yhid,username as yhmc from T_Sys_User a where a.userloginid=? ";
				} else if ("1".equals(tsysuser.getUsertype())) {
					user_hql = "  select userloginid as yhid,username as yhmc from T_Sys_User a where a.userloginid=? ";
				} else {
					user_hql = "  select userloginid as yhid,username as yhmc from T_Sys_User a where a.userloginid=? ";
				}
				List<Object> params = new LinkedList<Object>();
				params.add(userLoginId);
				List<ResourceForshdEntity> resourceForshdEntitiesList = DBUtil.queryAllBeanList(user_hql, ResourceForshdEntity.class, userLoginId);
				//不知道这是谁写的“&”。。。if (null != resourceForshdEntitiesList & resourceForshdEntitiesList.size() > 0) {
				if (null != resourceForshdEntitiesList && resourceForshdEntitiesList.size() > 0) {
					entity = resourceForshdEntitiesList.get(0);
				}
				CacheUtils.put(cacheKey, entity); // 缓存
			}
		}
		return entity;
	}

	/**
	 * 断言接入号合法性；断言接入站点就是登记注册时填写的网址
	 *
	 * @param clientAppId 加密的接入号
	 * @return 解密后的接入号
	 */
	public String checkClientAppIdShd(String clientAppId) {
		if (StringUtils.isBlank(clientAppId)) {
			LOG.error("接收到一次非法的请求 [ miss ClientAppId ] ");
			throw new RuntimeException("非法请求！");
		} else {
			clientAppId = CipherUtil.decryptByAES(clientAppId); // 解密
			String cacheKey = "AuthApp" + clientAppId;
			TAccessAppReg appReg = (TAccessAppReg) CacheUtils.get(cacheKey); // 缓存
			if (appReg == null) {
				List<TAccessAppReg> appRegs = baseDao.findByHqlWithSecondCache(true, "from TAccessAppReg where appid=?", clientAppId);
				if (appRegs == null || appRegs.isEmpty()) {
					LOG.error("接收到一次无效的请求 [ not exist ClientAppId : " + clientAppId + " ] ");
					throw new RuntimeException("无效请求！");
				} else { // 缓存起来
					CacheUtils.put(cacheKey, appRegs.get(0));
				}
			}
		}
		return clientAppId;
	}

}
